import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:sph_shipper/AppConfig/ShowDialog.dart';
import 'package:sph_shipper/SendGoods/FrequentlyShippedSources.dart';
import 'package:sph_shipper/http/NoLoadingPostApi.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../Main/MyWallet/PayAuthentication.dart';
import '../../TabBar/TabbarView.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/api.dart';
import 'FreightPaymentSuccessful.dart';

class PayTheFreight extends StatefulWidget {
  const PayTheFreight({super.key, required this.dataMap, required this.payType, required this.payId});
  final Map dataMap;
  final int payType;
  final String payId;
  @override
  State<PayTheFreight> createState() => _PayTheFreightState();
}


class _PayTheFreightState extends State<PayTheFreight> {

  int payType=-1;
  int allMoney=0;
  Map userMap={};
  String userMoney="";
  bool walletType=false;
  String phoneNum="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo();

  }
void getUserInfo()async{
  phoneNum=(await PhoneNumManager.getPhone())!;
  NoLoadinggetApiManager.getData(
    context, // 上下文对象，用于显示提示信息等
    'api/pay/shipper/user/balanceInfo', // 您的API端点
    {}, // 查询参数，如果没有可以传递null
        (responseData)  {
      setState(() {
        userMoney=responseData['data']['balance'].toString();
        if(responseData['data']['passwordStatus']!=null&&responseData['data']['passwordStatus']==1){
          walletType=true;
        }else{
          walletType=false;
        }

      });
    },
  );
}
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
          leading: IconButton(
            onPressed: () {

              NoLoadingApiManager.postData(
                context,
                "api/pay/shipper/user/cancelPayFreight",
                {
                  "billId":widget.payId,
                },
                    (responseData)  {
                Navigator.pop(context);
                },
              );
            },
            icon: Icon(Icons.arrow_back_ios),
          ),
        title:Text( "支付",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
      backgroundColor: Colors.white,
      centerTitle: true,
        ),

      body:Column(
        children: [
          Expanded(child: ListView(
            children: [
          Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
            padding: EdgeInsets.only(left: 18.w,top: 9.h,bottom: 9.h),
            decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
            child:Column(
              crossAxisAlignment: CrossAxisAlignment.start,
            children: [

                  Text("运单号"+"      "+widget.dataMap['id'],style:TextStyle(color: Colors.black,fontSize: 14.sp),),
              Text("运单信息"+"   "+widget.dataMap['goodsInfo']['loadPlaceInfo'][0]['city']+"——"+widget.dataMap['goodsInfo']['unloadPlaceInfo'][0]['city'],style:TextStyle(color: Colors.black,fontSize: 14.sp),),
            ],
          ),
          ),
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(top: 22.h,bottom: 23.h),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                     Row(
                       mainAxisAlignment: MainAxisAlignment.center,
                       crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                              Text("运费 ¥",style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontWeight: FontWeight.w600,fontSize: 14.sp),),
                               Text((widget.dataMap['freight']).toString(),style: TextStyle(color: Color.fromRGBO(228, 28, 35, 1),fontSize: 20.sp,fontWeight: FontWeight.w600),),
                        ],
                    ),

                    Container(
                      padding: EdgeInsets.all(10.h),
                      margin: EdgeInsets.only(top: 14.h),
                      width: screenSize.width-20.w,
                      height: 40.h,
                      color: Color.fromRGBO(251, 241, 233, 1),
                      child: Text("请选择支付方式",style: TextStyle(color: MyColors.themeColor),),
                    ),
                    SizedBox(height: 10.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/余额支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text("余额支付",style: TextStyle(color: Colors.black,),),
                                Text("可用"+userMoney+"元",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                              ],
                            ),

                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=1;
                          });
                        }, icon:payType==1?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/微信支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("微信支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=2;
                          });
                        }, icon:payType==2?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/支付宝支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("支付宝支付",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        IconButton(onPressed: (){
                          setState(() {
                            payType=3;
                          });
                        }, icon:payType==3?Icon(Icons.check_circle,color: MyColors.themeColor,):Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10.w,),
                            Image.asset("lib/Images/OrderList/银行卡支付.png",width: 30.w,height: 30.h,),
                            SizedBox(width: 6.w,),
                            Text("招商银行储蓄卡(9999)",style: TextStyle(color: Colors.black,),),
                          ],
                        ),
                        Row(
                          children: [
                            BrnTagCustom.buildBorderTag(
                              tagText: '支付立减6.9元',
                              textColor:Color.fromRGBO(246, 57, 13, 1),
                              borderColor: Color.fromRGBO(246, 57, 13, 1),
                              borderWidth: 1,
                              fontSize: 12.sp,
                            ),
                            IconButton(onPressed: (){
                              setState(() {
                                payType=4;
                              });

                            }, icon:payType==4?Icon(Icons.check_circle,color: MyColors.themeColor,): Icon(Icons.panorama_fish_eye,color: MyColors.authTipColor,) ),
                          ],
                        ),
                      ],
                    ),
                    Divider(height: 20.h,color: MyColors.backgreyColor,),
                    GestureDetector(
                      child:  Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("    "+"其他付款方式",style: TextStyle(color: Colors.black),),
                          Row(
                            children: [
                              Text("其他付款方式",style: TextStyle(color:MyColors.authTipColor),),
                              Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 14,),
                              SizedBox(width: 10.w,),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
               ),

            ], 
          ),
          ),
          Container(
            color: Colors.white,
            width: screenSize.width,
            height: 85.h,
            padding: EdgeInsets.only(top: 10.h,right: 15.w,left: 15.w,bottom: 40.h),
            child:BrnSmallMainButton(
              title: '立即支付',
              textColor: Colors.white,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              bgColor: MyColors.themeColor,
              radius: 30,
              onTap: () {
                if(payType==-1){
                  BrnToast.show("请选择支付方式", context, duration: BrnDuration.short,);
                }else if(payType==1){
                  if(walletType){

                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return payThefreightPassDailog(dataMap: widget.dataMap, payType: widget.payType, payId:widget.payId,

                        );
                      },
                    );
                  }else{
                    showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return BrnDialog(
                          titleText: "温馨提示",
                          messageText: "您尚未设置支付密码，请前往设置。",
                          actionsWidget: [
                            TextButton(
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              child: Text("我再想想",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                            ),
                            TextButton(
                              onPressed: () async{
                                Navigator.pop(context);
                                final result=await  Navigator.push( context, FadeRoute(page:PayAuthentication(phoneNum:phoneNum ,)));
                                if(result!=null){
                                  getUserInfo();
                                }
                              },
                              child: Text("现在就去",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                            ),
                          ],
                        );
                      },
                    );
                  }

                }

              },
            ),
          )
        ],
      ) ,
    );
  }
}
class payThefreightPassDailog extends StatefulWidget {
  const payThefreightPassDailog({super.key, required this.dataMap, required this.payType, required this.payId});
  final Map dataMap;
  final int payType;
  final String payId;
  @override
  State<payThefreightPassDailog> createState() => _payThefreightPassDailogState();
}

class _payThefreightPassDailogState extends State<payThefreightPassDailog> {
  TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Container(
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(),
                IconButton(
                  icon: Icon(Icons.close,color: MyColors.authTipColor,),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),

            Text(
              '请输入支付密码',
              style: TextStyle(
                color:MyColors.textColor,
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 16),
            Container(
              margin: EdgeInsets.only(left: 10.w,right:10.w),
              child: PinCodeTextField(
                  obscureText:true,
                  appContext: context,//context
                  length: 6,//输入的长度
                  controller: _controller,
                  autoFocus: true,
                  textStyle:TextStyle(color: Colors.black),
                  cursorColor: Colors.black,
                  pinTheme: PinTheme(
                    shape: PinCodeFieldShape.box, //输入框的形状
                    borderRadius: const BorderRadius.all(Radius.circular(0)),
                    activeColor:MyColors.themeColor,
                    selectedColor:MyColors.authTipColor,
                    inactiveColor:MyColors.backgreyColor,

                  ),

                  onChanged: (value)  async {
                    if(value.length==6) {
                      if (widget.payType == 2) {
                        // ApiManager.postData(
                        //   context,
                        //   'api/pay/shipper/user/doPayFreight',
                        //   {
                        //     "billId":widget.dataMap['id'],
                        //     "channel": "WALLET",
                        //     "password": value
                        //   },
                        //       (responseData) {
                        //         BrnToast.show(
                        //           "支付成功",
                        //           context,
                        //           duration: BrnDuration.short,
                        //         );
                        //         Navigator.pushReplacement(
                        //           context,
                        //           MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                        //         );
                        //   },
                        // );
                       }else{
                          print(widget.payId);
                        ApiManager.postData(
                          context,
                          'api/pay/shipper/user/doPayFreight',
                          {
                            "billId":widget.payId,
                            "channel": "WALLET",
                            "password": value
                          },
                              (responseData) {
                            BrnToast.show(
                              "支付成功",
                              context,
                              duration: BrnDuration.short,
                            );
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,),fullscreenDialog: true,),
                            );
                          },
                        );
                      }
                    }
                  }
              ),
            ),

            SizedBox(height: 16),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                // Navigator.push(context,
                //     MaterialPageRoute(builder: (context) {
                //       return FrequentlyShippedSources(
                //
                //       );
                //     }));
              },
              child: Text('忘记密码？',
                style: TextStyle(
                  color: MyColors.themeColor,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

